package tech.aistar.corejava.day15.Synchronizeddemo;

/**
 * Created by 豆梦寒 on 2019/8/3.
 */


/**
 * 老公取款..
 * 老公完成取款,余额是:90
 * 老公取款..
 * 老公完成取款,余额是:80
 * 老婆取款..
 * 老婆完成取款,余额是:70
 * ...
 * ...
 */
public class AccountDemo {
    public static void main(String[] args) {
        //创建一个线程
        Runnable r = new AccountThread();


        Thread husband = new Thread(r);
        husband.setName("文章:");

        Thread wife = new Thread(r);
        wife.setName("马伊琍:");
        husband.start();
        wife.start();


    }

}
class AccountThread implements Runnable{
    //临界资源
    private Account acc = new Account();


    //同步代码 方式   一般不推荐
//    public  synchronized void withdraw1(double money){
//        System.out.println(Thread.currentThread().getName()+"正在取款");
//        acc.withdraw(money);
//
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        System.out.println(Thread.currentThread().getName()+"完成取款，余额是"+acc.getMoney());
//    }
    //同步代码块  推荐
    public void withdraw(double money){
        synchronized (acc){//acc临界资源对象
            System.out.println(Thread.currentThread().getName()+"正在取款");
            acc.withdraw(money);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"完成取款，余额是"+acc.getMoney());
        }
    }


    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            withdraw(10);
        }
    }
    //临界资源
}
